const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const fs = require('fs');
const userDataPath = app.getPath('userData')
const emailFilePath = path.join(userDataPath, 'email.json');
const HuffmanCoder = require('../n-api')
var emailData = [];

function saveEmailData(){
  fs.writeFileSync(emailFilePath, JSON.stringify({data: emailData}));
}

function decodeBinary(binary) {
  const lengthBinary = binary.substring(0, 8);
  const length = parseInt(lengthBinary, 2);
  const contentBinary = binary.substring(8 + length);
  return contentBinary;
}
function bufferToBinaryString(buffer) {
  let binaryString = '';
  for (let i = 0; i < buffer.length; i++) {
      // 对每个字节进行位操作，并转换为二进制字符串
      const byte = buffer[i];
      for (let j = 7; j >= 0; j--) { // 从最高位开始
          // 使用位与(&)和位移(>>)操作来检查当前位是否为1
          binaryString += (byte & (1 << j)) ? '1' : '0';
      }
      // 如果你想在每个字节之间添加空格或其他分隔符，可以在这里添加
  }
  return binaryString;
}
function getEmail(id) {
  const dataString = fs.readFileSync(path.join(userDataPath, './email/', id+'.json'))
  const data = JSON.parse(dataString)
  const freqMap = data['freqMap']
  const emailBin = fs.readFileSync(path.join(userDataPath, './email/', id+'.bin'));
  const huffmanCode = decodeBinary(bufferToBinaryString(emailBin));
  content = HuffmanCoder.decode(huffmanCode, freqMap);
  return content;
}

function generateBinary(string){
    const length = string.length; 
    // 填充0的数量
    const padding = (length % 8 === 0) ? 0 : (8 - (length % 8));
    const padBinary = padding.toString(2).padStart(8, '0'); // 00000000 ~ 00000111
    // 不足8的倍数的部分填充0
    const paddedBinaryString = string.padStart(length + padding, '0');

    const fullBinaryString = padBinary + paddedBinaryString; // 000000000 + ...

    // 将二进制字符串按每8位一组分割
    const byteArray = [];
    for (let i = 0; i < fullBinaryString.length; i += 8) {
        const byteString = fullBinaryString.slice(i, i + 8);
        byteArray.push(parseInt(byteString, 2));
    }
    return Buffer.from(byteArray);
}

function saveEmail(id, data) {
  data["id"] = id;
  data['freqMap'] = HuffmanCoder.generateFreqMap(data['content']);
  content = HuffmanCoder.encode(data['content'], data['freqMap']);
  delete data['content'];
  binary = generateBinary(content);
  fs.writeFileSync(path.join(userDataPath, './email/', id+'.json'), JSON.stringify(data));
  fs.writeFileSync(path.join(userDataPath, './email/', id+'.bin'), binary);
  emailData.push(data);
  saveEmailData()
}

async function refreshEmailData(){
    return await new Promise((resolve) => {
        fs.stat(emailFilePath, (err) => {
            if (err) {
                fs.writeFile(emailFilePath, JSON.stringify({data: []}), () => {});
                resolve({});
            } else {
                fs.readFile(emailFilePath, 'utf8', (err, data) => {
                    if (err) {
                        console.error('Error reading email.json:', err);
                        return;
                    }
                    try {
                        emailData = JSON.parse(data).data;
                        resolve({}) 
                    } catch (e) {
                        console.error('Error parsing email.json:', e);
                    }
                });
            }
        });
        fs.stat(path.join(userDataPath, './email'), (err) => {
            if (err) {
                fs.mkdir(path.join(userDataPath, './email'), () => {});
            }
        });
    })
}

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 1000,
    height: 800,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
    },
  });

  mainWindow.loadFile('./src/login.html');

  ipcMain.on('navigate', (event, page) => {
    if (page === 'inbox') {
      mainWindow.loadFile('./src/inbox.html');
    } else if (page.startsWith('email')) {
      mainWindow.loadFile('./src/email.html');
    } else if (page === 'writeEmail') {
      mainWindow.loadFile('./src/writeEmail.html');
    }else {
      mainWindow.loadFile('./src/login.html');
    }
  });
  ipcMain.on("add-email", (event, data) => {
    // data = {
    //   recipient: recipient,
    //   subject: subject,
    //   content: content
    // }
    const id = Date.now().toString();
    saveEmail(id, data);
    event.reply("email-added", 1);
  });
  ipcMain.on("set-email", (event, emailId) => {
    emailData.forEach((email) => {
      if (email.id === emailId) {
        email["content"] = getEmail(email.id);
        event.reply("get-email", email);
      }
    });
  });
  ipcMain.on("set-email-list", (event, data) => {
    refreshEmailData().then(()=>{
      event.reply("get-email-list", emailData);
    })
  });
}

app.on('ready', ()=>{
    createWindow();
    fs.stat(emailFilePath, (err) => {
        if (err) {
            fs.writeFile(emailFilePath, JSON.stringify({data: []}), () => {});
        } else {
            fs.readFile(emailFilePath, 'utf8', (err, data) => {
                if (err) {
                    console.error('Error reading email.json:', err);
                    return;
                }
                try {
                    emailData = JSON.parse(data).data;
                } catch (e) {
                    console.error('Error parsing email.json:', e);
                }
            });
        }
    });
    fs.stat(path.join(userDataPath, './email'), (err) => {
        if (err) {
            fs.mkdir(path.join(userDataPath, './email'), () => {});
        }
    });
});

app.on('window-all-closed', () => {
    saveEmailData()
    if (process.platform !== 'darwin') {
      app.quit();
    }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});
// 在主进程或渲染进程中
process.on('uncaughtException', (err) => {
  console.error('未捕获的异常：', err);
  // 可以选择在这里进行错误记录或显示错误对话框
  // 例如，在Electron主进程中可以使用dialog模块来显示错误
  // 注意：在渲染进程中，你可能需要发送消息到主进程来显示对话框
});